package com.dpad.telematicsclientapp.ui

import android.Manifest
import android.app.Dialog
import android.content.Intent
import android.graphics.Point
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.dpad.crmclientapp.android.util.utils.*
import com.dpad.telematicsclientapp.Constance
import com.dpad.telematicsclientapp.android.R
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.CardItem3
import com.dpad.telematicsclientapp.mvp.imageloader.ILFactory
import com.dpad.telematicsclientapp.mvp.imageloader.ILoader
import com.dpad.telematicsclientapp.mvp.kit.Kits
import com.dpad.telematicsclientapp.netlibrary.Contances
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.AppManager
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyActivity
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.SplashBean2
import com.dpad.telematicsclientapp.presenter.SplashPresenter
import com.dpad.telematicsclientapp.util.PreferenceUtils
import com.dpad.telematicsclientapp.util.ToolKit
import com.dpad.telematicsclientapp.util.utils.*
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_sp.*

import rx.subscriptions.CompositeSubscription

/**
 * ================================================
 * 作    者：wenbody
 * 版    本：1.0
 * 创建日期：2019/12/30 13:45
 * 描    述：
 * 修订历史：
 * ================================================
 */
class SplashActivity : BaseCopyActivity<SplashPresenter>() {

    private val mHandler: Handler = Handler()
    private var mCount = 5

    //屏幕的宽x  高 y
    var x = 0;
    var y = 0;

    override fun initPageData() {
        StatusBarUtils.with(this)
                .init()


//        if (checkAgreeMentsStatus()) {
//            getP().tokenLogin()
//        } else {
//            startActivityForResult(Intent(this, AgreementActivity::class.java), 66)
//        }
        checkPermission()
    }


    /**
     * 是否同意过协议
     */
    private fun checkAgreeMentsStatus(): Boolean {
        val isAgree = PreferenceUtils.getInstance(this).getBoolean(Constant.KEY_AGREEMENT)
        val versionCode = PreferenceUtils.getInstance(this).getString(Constant.KEY_VERSIONCODE)

        return isAgree && !Kits.Empty.check(versionCode) && versionCode.toInt() == Kits.Package.getVersionCode(this)
    }

    override fun getLayout(): Int {
        return R.layout.activity_sp
    }

    override fun newPresenter(subscriptions: CompositeSubscription?): SplashPresenter {
        return SplashPresenter()
    }

    override fun getPageTitle(): String {
        return "启动页"
    }

    /**
     * 需要设备标识码权限
     */
    private fun checkPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION).subscribe { aBoolean ->
            if (aBoolean) {
//                getP().getLocationData()
                if (checkAgreeMentsStatus()) {
                    getP().tokenLogin()
                } else {
//                    startActivityForResult(Intent(this, AgreementActivity::class.java), 66)

                    ARouter.getInstance()
                            .build(Contances.URL_ACTIVITY_AGREE, Contances.GROUP_OTHER)
                            .navigation(this@SplashActivity,66)

                }
            } else {
                val title = UIUtils.getString(R.string.dialog_warning_title)
                val content = UIUtils.getString(R.string.permission_device_error)
                DialogUtil.showPermissionSettingDialog(this, title, content) { dialog: Dialog, confirm: Boolean ->
                    if (confirm) { //跳转系统权限设置界面
                        val packageURI = Uri.parse("package:" + this.packageName)
                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                        this.startActivityForResult(intent, Constant.STARTACTIVITY_PREMISSION)
                        dialog.dismiss()
                    } else {
                        AppManager.getInstance().exitApp(this)
                        dialog.dismiss()
                    }
                }
            }
        }
    }

    fun showSplash(bean: SplashBean2) {
        if (bean.result != null) {

            if (bean.result.size>0){
                //获取屏幕的宽高
                val defaultDisplay = getWindowManager().getDefaultDisplay()
                val point =  Point()
                defaultDisplay.getSize(point)
                x = point.x;
                y = point.y;

//                if (!Kits.Empty.check(bean.result.get(0).picUrl) && !Kits.Empty.check(bean.result.get(0).link)) {//证明至少有图片
                    if (!Kits.Empty.check(bean.result.get(0).picUrl) ) {//证明至少有图片
                        val options: ILoader.Options = ILoader.Options(R.mipmap.login_icon2, R.mipmap.login_icon2)
                        var imageUrl="";
                        var picsize=bean.result.size
                        imageUrl = ToolKit.getImageUrl(bean,y,x);
                        if(picsize>0){
                            ILFactory.getLoader().loadNet(splashIm, imageUrl, options);
                        }

                    splashIm.setOnClickListener {
                        val bundle = Bundle()
                        bundle.putSerializable("url_tag", bean.result.get(0).link)

//                        val intent = Intent(this, WebViewActivity::class.java)
//                        intent.putExtra("bundle", bundle)
//                        startActivity(intent)

                        ARouter.getInstance()
                                .build(Contances.URL_ACTIVITY_WEB, Contances.GROUP_OTHER)
                                .withBundle("bundle",bundle)
                                .navigation(this@SplashActivity)


                    }
                    jumpHomeTv.visibility = View.VISIBLE
                    requestSendVerifyNumber()
                    jumpHomeTv.setOnClickListener {
                        removeRunable()
                        getP().jumpToHome()
                    }
                } else {
                    getP().jumpToHome()
                }
            }else{
                getP().jumpToHome()
            }

        } else {
            getP().jumpToHome()
        }
    }
    fun showListViewData(result: List<CardItem3.ResultBean?>?) {
        if (result != null) {
            if (result.size>0) { //当T车列表长度大于0的时候，则证明有T车，且所有车辆未激活，此时跳转到T激活首页
//                val intent2 = Intent(this, TChooseCarActivity3::class.java)
//                intent2.putExtra("type", "0")
//                startActivity(intent2)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_TChooseCar, Contances.GROUP_MYCAR)
                        .withString("type", "0")
                        .navigation(this@SplashActivity)


            } else {
                T.showToastSafeError("暂未查到您的合同信息")
            }
        } else {
            T.showToastSafeError("暂未查到您的合同信息")
        }
    }

    private val countDown = object : Runnable {
        override fun run() {
            jumpHomeTv.text = "跳过" + mCount
            if (mCount > 0) {
                mHandler.postDelayed(this, 1000)
                mCount--
            } else {
                mCount = 0
                getP().jumpToHome()
                removeRunable()
            }

        }
    }

    /*
      倒计时，并处理点击事件
   */
    private fun requestSendVerifyNumber() {
        mHandler.postDelayed(countDown, 0)
    }

    private fun removeRunable() {
        mHandler.removeCallbacks(countDown)
    }

    override fun onBackPressed() {
        return
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constant.STARTACTIVITY_PREMISSION) {
            checkPermission()
        } else if (requestCode == 66) {
//            checkPermission()
            getP().tokenLogin()
        }
    }
}